<template>
  <view class="test-page">
    <view class="header">
      <text class="title">登录功能测试页面</text>
      <text class="subtitle">用于测试抖音小程序登录功能</text>
    </view>

    <view class="content">
      <!-- 环境信息 -->
      <view class="env-info">
        <text class="env-title">当前环境信息：</text>
        <text class="env-text">环境类型: {{ envInfo.env }}</text>
        <text class="env-text">是否抖音小程序: {{ envInfo.isDouyin ? '是' : '否' }}</text>
        <text class="env-text">是否H5: {{ envInfo.isH5 ? '是' : '否' }}</text>
      </view>

      <!-- 登录状态 -->
      <view class="login-status">
        <text class="status-title">登录状态：</text>
        <text class="status-text">已登录: {{ isLoggedIn ? '是' : '否' }}</text>
        <text v-if="userInfo" class="status-text">用户ID: {{ userInfo.userId }}</text>
        <text v-if="userInfo" class="status-text">OpenID: {{ userInfo.openid }}</text>
      </view>

      <!-- 操作按钮 -->
      <view class="actions">
        <button class="action-btn" @click="checkLoginStatus">检查登录状态</button>
        <button class="action-btn" @click="triggerLogin">手动登录</button>
        <button class="action-btn" @click="getUserInfo">获取用户信息</button>
        <button class="action-btn" @click="clearLogin">清除登录</button>
        <button class="action-btn test-401-btn" @click="test401Error">测试401错误处理</button>
      </view>

      <!-- 日志信息 -->
      <view class="logs">
        <text class="logs-title">操作日志：</text>
        <scroll-view class="logs-content" scroll-y>
          <text v-for="(log, index) in logs" :key="index" class="log-item">
            {{ log }}
          </text>
        </scroll-view>
      </view>
    </view>

    <!-- 静默登录组件 -->
    <SilentLogin 
      ref="silentLogin"
      :auto-login="true"
      :delay-show="1000"
      @login-success="onLoginSuccess"
      @login-cancel="onLoginCancel"
    />
  </view>
</template>

<script>
import { ref, onMounted } from 'vue';
import SilentLogin from '../../components/SilentLogin.vue';

export default {
  name: 'TestLogin',
  components: {
    SilentLogin
  },
  setup() {
    const isLoggedIn = ref(false);
    const userInfo = ref(null);
    const logs = ref([]);
    const silentLogin = ref(null);

    // 环境信息
    const envInfo = ref({
      env: 'unknown',
      isDouyin: false,
      isH5: false
    });

    // 添加日志
    const addLog = (message) => {
      const timestamp = new Date().toLocaleTimeString();
      logs.value.unshift(`[${timestamp}] ${message}`);
      if (logs.value.length > 20) {
        logs.value.pop();
      }
    };

    // 检查环境
    const checkEnvironment = () => {
      const isDouyin = typeof tt !== 'undefined';
      const isH5 = typeof window !== 'undefined' && typeof document !== 'undefined';
      
      envInfo.value = {
        env: isDouyin ? 'douyin' : isH5 ? 'h5' : 'unknown',
        isDouyin,
        isH5
      };
      
      addLog(`环境检测完成: ${envInfo.value.env}`);
    };

    // 检查登录状态
    const checkLoginStatus = () => {
      if (silentLogin.value) {
        const status = silentLogin.value.checkLoginStatus();
        addLog(`登录状态检查: ${status ? '已登录' : '未登录'}`);
        return status;
      }
      addLog('登录状态检查: 组件未初始化');
      return false;
    };

    // 手动登录
    const triggerLogin = async () => {
      addLog('开始手动登录');
      if (silentLogin.value) {
        try {
          await silentLogin.value.triggerLogin();
          addLog('手动登录完成');
        } catch (error) {
          addLog(`手动登录失败: ${error.message}`);
        }
      } else {
        addLog('登录组件未初始化');
      }
    };

    // 获取用户信息
    const getUserInfo = () => {
      if (silentLogin.value) {
        const info = silentLogin.value.getUserInfo();
        addLog(`获取用户信息: ${JSON.stringify(info)}`);
        return info;
      }
      addLog('获取用户信息失败: 组件未初始化');
      return null;
    };

    // 清除登录
    const clearLogin = () => {
      isLoggedIn.value = false;
      userInfo.value = null;
      addLog('登录状态已清除');
    };

    // 测试401错误处理
    const test401Error = async () => {
      addLog('开始测试401错误处理');
      try {
        // 先清除登录状态，确保没有token
        clearLogin();
        
        // 等待一下让状态更新
        await new Promise(resolve => setTimeout(resolve, 100));
        
        // 尝试调用一个需要登录的API（这会触发401错误）
        addLog('尝试调用需要登录的API...');
        
        // 动态导入API函数
        const { generateImages } = await import('../../services/api/backendApi.js');
        
        // 调用一个需要登录的API，应该会返回401
        await generateImages('test_analysis_id');
        
        addLog('API调用成功（不应该到这里）');
      } catch (error) {
        addLog(`API调用失败: ${error.message}`);
        if (error.message.includes('未授权') || error.message.includes('401')) {
          addLog('✅ 成功触发401错误处理');
        } else {
          addLog('❌ 未触发预期的401错误处理');
        }
      }
    };

    // 登录成功回调
    const onLoginSuccess = (info) => {
      isLoggedIn.value = true;
      userInfo.value = info;
      addLog(`登录成功: ${JSON.stringify(info)}`);
    };

    // 登录取消回调
    const onLoginCancel = () => {
      addLog('用户取消登录');
    };

    onMounted(() => {
      addLog('页面加载完成');
      checkEnvironment();
    });

    return {
      isLoggedIn,
      userInfo,
      logs,
      envInfo,
      silentLogin,
      checkLoginStatus,
      triggerLogin,
      getUserInfo,
      clearLogin,
      test401Error,
      onLoginSuccess,
      onLoginCancel
    };
  }
};
</script>

<style lang="scss" scoped>
.test-page {
  padding: 20rpx;
  background: #f5f5f5;
  min-height: 100vh;
}

.header {
  text-align: center;
  margin-bottom: 40rpx;
  
  .title {
    display: block;
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 10rpx;
  }
  
  .subtitle {
    display: block;
    font-size: 28rpx;
    color: #666;
  }
}

.content {
  background: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.env-info, .login-status {
  margin-bottom: 30rpx;
  
  .env-title, .status-title {
    display: block;
    font-size: 30rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 15rpx;
  }
  
  .env-text, .status-text {
    display: block;
    font-size: 26rpx;
    color: #666;
    margin-bottom: 8rpx;
  }
}

.actions {
  margin-bottom: 30rpx;
  
  .action-btn {
    width: 100%;
    height: 80rpx;
    background: #007aff;
    color: #fff;
    border: none;
    border-radius: 40rpx;
    font-size: 28rpx;
    margin-bottom: 20rpx;
    
    &:active {
      opacity: 0.8;
    }
    
    &.test-401-btn {
      background: #ff6b6b;
    }
  }
}

.logs {
  .logs-title {
    display: block;
    font-size: 30rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 15rpx;
  }
  
  .logs-content {
    height: 300rpx;
    background: #f8f8f8;
    border-radius: 10rpx;
    padding: 20rpx;
    
    .log-item {
      display: block;
      font-size: 24rpx;
      color: #666;
      margin-bottom: 8rpx;
      font-family: monospace;
    }
  }
}
</style>
